package personal.wang.proxyAndPekko;

import com.typesafe.config.ConfigFactory;
import org.apache.pekko.actor.AbstractActor;
import org.apache.pekko.actor.ActorSystem;
import org.apache.pekko.actor.Props;
import personal.wang.proxy.Factory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Collectors;

public class RpcServer extends AbstractActor {

    public static void main(String[] args) {
        Factory factory = new Factory() ;
        RpcServer.builder(factory);

    }

    public static void builder(Object target){
        ActorSystem actorSystem = ActorSystem.create("flink", ConfigFactory.load("test_server"));
        actorSystem.actorOf(Props.create(RpcServer.class , target) , "server");
    }

    private Object target ;

    public RpcServer(Object target){
        this.target = target ;
    }
    @Override
    public Receive createReceive() {
        return receiveBuilder().match(InvocationRequest.class , this::messageRequest).build();
    }

    private void messageRequest(InvocationRequest request) {
        System.out.println("aaa");
        String methodName = request.getMethodName();
        Object[] args = request.getArgs();
        Class<?>[] classArray = null ;
        if(Objects.nonNull(args) && args.length > 0){
            args = new Class[args.length];
            Arrays.stream(args).map(Object::getClass).collect(Collectors.toList()).toArray(classArray);
        }
        try {
            Method method = target.getClass().getMethod(methodName, classArray);
            method.invoke(target , args);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }


    }
}
